package org.feng.support.impl;

import cn.hutool.core.io.file.FileNameUtil;
import io.minio.*;
import org.feng.entity.PubResource;
import org.feng.entity.result.UploadResult;
import org.feng.support.UploadInterface;
import org.feng.support.proxy.ProxyUpload;
import org.feng.utils.UploadFileUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * minio
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
public class Minio implements UploadInterface {
    private PubResource pubResource;
    private MinioClient minioClient;

    public Minio(PubResource pubResource) {
        try {
            this.pubResource = pubResource;
            this.minioClient = MinioClient.builder()
                    .endpoint(pubResource.getEndpoint())
                    .credentials(pubResource.getKey(), pubResource.getSecret())
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public UploadResult putFile(MultipartFile file) {
        UploadResult uploadResult = ProxyUpload.checkMd5(file);
        if (uploadResult.getFileUrl() != null) {
            return uploadResult;
        }
        String filename = UploadFileUtils.getFileName(file.getOriginalFilename());
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(pubResource.getBucket())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(filename).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        uploadResult = new UploadResult();
        uploadResult.setFileName(file.getOriginalFilename());
        uploadResult.setFileUrl(getFileLink(filename));
        uploadResult.setFileSize(file.getSize());
        uploadResult.setFileType(FileNameUtil.extName(file.getOriginalFilename()));
        uploadResult.setFileMd5(uploadResult.getFileMd5());
        ProxyUpload.saveMd5(uploadResult);
        return uploadResult;
    }

    private String getFileLink(String fileName) {
        return this.pubResource.getEndpoint() + "/" + this.pubResource.getBucket() + "/" + fileName;
    }
}
